package com.ikingtech.framework.sdk.job.embedded.caller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.framework.sdk.context.security.Identity;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.enums.common.FrameworkServerFeedbackTypeEnum;
import com.ikingtech.framework.sdk.job.embedded.JobResolver;
import com.ikingtech.framework.sdk.job.model.rpc.JobExecuteInfo;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.support.server.FrameworkServerFeedbackCaller;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;

import static com.ikingtech.framework.sdk.context.constant.SecurityConstants.*;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class JobServerFeedbackCaller implements FrameworkServerFeedbackCaller {

    private final LoadBalancerClient loadBalancerClient;

    private final JobResolver resolver;

    @Override
    public R<Object> call(Object data) {
        JobExecuteInfo job = (JobExecuteInfo) data;
        if ("server".equals(job.getExecutorClientId())) {
            return this.resolver.resolve(job);
        }
        ServiceInstance client = this.loadBalancerClient.choose(job.getExecutorClientId());
        try {
            String resultStr = Tools.Http.post(Tools.Http.SCHEMA_HTTP + client.getHost() + ":" + client.getPort() + "/job/resolve",
                    Tools.Json.toJsonStr(job),
                    Tools.Coll.newMap(
                            Tools.Coll.Kv.of(HEADER_INNER_IDENTITY, Identity.inner()),
                            Tools.Coll.Kv.of(HEADER_CALLER, "INNER"),
                            Tools.Coll.Kv.of(HEADER_TENANT_CODE, job.getTenantCode())
                    ));
            return Tools.Json.toBean(resultStr, new TypeReference<>() {
            });
        } catch (Exception e) {
            return R.failed(e.getMessage());
        }
    }

    @Override
    public FrameworkServerFeedbackTypeEnum type() {
        return FrameworkServerFeedbackTypeEnum.JOB_FEEDBACK;
    }
}
